/**
 * 组件管理服务
 * 用于中央管理组件类型映射、标准化和组件实例
 */

import { markRaw } from 'vue';
import { ElButton, ElInput, ElSelect, ElOption, ElSwitch, ElCheckbox, ElRadio, ElTable, 
         ElTableColumn, ElTag, ElCard } from 'element-plus';

// 动态生成的组件别名映射和路径映射
let componentAliases = {};
let componentTypeToPath = {};

/**
 * Element Plus 组件映射
 */
const elementPlusComponents = {
  'el-button': ElButton,
  'el-input': ElInput,
  'el-select': ElSelect,
  'el-option': ElOption,
  'el-switch': ElSwitch,
  'el-checkbox': ElCheckbox,
  'el-radio': ElRadio,
  'el-table': ElTable,
  'el-table-column': ElTableColumn,
  'el-tag': ElTag,
  'el-card': ElCard,
};

/**
 * 标准HTML元素映射
 */
const htmlElements = {
  'div': 'div',
  'span': 'span',
  'p': 'p',
  'h1': 'h1',
  'h2': 'h2',
  'h3': 'h3',
};

/**
 * 组件实例缓存
 */
const componentInstanceCache = new Map();

/**
 * 组件管理服务类
 */
class ComponentManagerService {
  constructor() {
    this.componentInstances = {};
    this.componentMap = null;
    
    // 设置Element Plus组件
    Object.entries(elementPlusComponents).forEach(([key, component]) => {
      this.componentInstances[key] = markRaw(component);
    });
    
    // 设置HTML元素
    Object.entries(htmlElements).forEach(([key, element]) => {
      this.componentInstances[key] = element;
    });
  }
  
  /**
   * 初始化所有组件实例
   */
  initializeComponents(componentRegistry) {
    if (!componentRegistry) return;
    
    let registeredCount = 0;
    for (const [name, component] of Object.entries(componentRegistry)) {
      this.registerComponent(name, component);
      registeredCount++;
    }
    
    console.log(`[ComponentManager] 初始化完成: ${registeredCount}个组件已注册`);
  }
  
  /**
   * 更新组件映射和别名
   */
  updateComponentMappings(mappings) {
    if (mappings.componentAliases) {
      componentAliases = mappings.componentAliases;
      console.log(`[ComponentManager] 更新别名映射: ${Object.keys(componentAliases).length}个`);
    }
    
    if (mappings.componentPaths) {
      componentTypeToPath = mappings.componentPaths;
      console.log(`[ComponentManager] 更新路径映射: ${Object.keys(componentTypeToPath).length}个`);
    }
    
    if (mappings.componentMap) {
      this.componentMap = mappings.componentMap;
      console.log(`[ComponentManager] 更新组件配置: ${this.componentMap.size}个`);
    }
  }
  
  /**
   * 注册单个组件
   */
  registerComponent(type, component) {
    if (!type || !component) return;
    
    const normalizedType = this.normalizeComponentType(type);
    this.componentInstances[normalizedType] = markRaw(component);
    
    // 保留原始类型映射
    if (type !== normalizedType) {
      this.componentInstances[type] = markRaw(component);
    }
    
    // 兼容性处理：也注册不带前缀的版本
    if (normalizedType.startsWith('ew-')) {
      const baseType = normalizedType.substring(3);
      if (!this.componentInstances[baseType]) {
        this.componentInstances[baseType] = markRaw(component);
      }
    }
  }
  
  /**
   * 标准化组件类型
   */
  normalizeComponentType(type) {
    if (!type) return 'div';
    
    // 别名映射
    if (componentAliases[type]) {
      return componentAliases[type];
    }
    
    // 已经有ew-前缀
    if (type.startsWith('ew-')) {
      return type;
    }
    
    // 尝试添加标准前缀
    const ewPrefixType = `ew-${type}`;
    if (componentAliases[ewPrefixType]) {
      return componentAliases[ewPrefixType];
    }
    
    // 自定义路径保留原样
    if (type.includes('/')) {
      return type;
    }
    
    return type;
  }
  
  /**
   * 获取组件路径
   */
  getComponentPath(type) {
    const normalizedType = this.normalizeComponentType(type);
    
    // 直接查找
    if (componentTypeToPath[normalizedType]) {
      return componentTypeToPath[normalizedType];
    }
    
    // 特殊处理带前缀类型
    if (normalizedType.startsWith('ew-')) {
      const baseType = normalizedType.substring(3);
      
      // 检查基本类型的路径
      if (componentTypeToPath[baseType]) {
        return componentTypeToPath[baseType];
      }
      
      // 尝试基本路径格式
      const basePath = `basic/${baseType}`;
      if (Object.values(componentTypeToPath).includes(basePath)) {
        return basePath;
      }
    }
    
    return null;
  }
  
  /**
   * 获取组件实例
   */
  getComponentInstance(type) {
    // HTML元素
    if (htmlElements[type]) {
      return htmlElements[type];
    }
    
    // 直接命中
    if (this.componentInstances[type]) {
      return this.componentInstances[type];
    }
    
    // 标准化后查找
    const normalizedType = this.normalizeComponentType(type);
    if (normalizedType !== type && this.componentInstances[normalizedType]) {
      return this.componentInstances[normalizedType];
    }
    
    // 尝试不带前缀版本
    if (normalizedType.startsWith('ew-')) {
      const baseType = normalizedType.substring(3);
      if (this.componentInstances[baseType]) {
        return this.componentInstances[baseType];
      }
    }
    
    // Element Plus组件
    if (elementPlusComponents[type]) {
      return elementPlusComponents[type];
    }
    
    return 'div';
  }
  
  /**
   * 获取组件配置
   */
  getComponentConfig(type) {
    if (!this.componentMap) {
      console.warn('[ComponentManager] 组件映射尚未初始化');
      return null;
    }
    
    const normalizedType = this.normalizeComponentType(type);
    const baseType = normalizedType.startsWith('ew-') ? normalizedType.substring(3) : normalizedType;
    
    // 尝试直接获取
    if (this.componentMap.has(normalizedType)) {
      return this.componentMap.get(normalizedType);
    }
    
    // 尝试基本类型
    if (this.componentMap.has(baseType)) {
      return this.componentMap.get(baseType);
    }
    
    return null;
  }
  
  /**
   * 异步加载组件模块
   */
  async loadComponentModule(type, moduleName) {
    const path = this.getComponentPath(type);
    if (!path) return null;
    
    const cachedKey = `${path}/${moduleName}`;
    if (componentInstanceCache.has(cachedKey)) {
      return componentInstanceCache.get(cachedKey);
    }
    
    try {
      const module = await import(/* @vite-ignore */ `../components/library/${path}/${moduleName}.js`);
      const result = module.default || module;
      componentInstanceCache.set(cachedKey, result);
      return result;
    } catch (error) {
      return null;
    }
  }
  
  /**
   * 加载组件预览处理模块
   */
  async loadPreviewHandler(type) {
    return this.loadComponentModule(type, 'preview');
  }
  
  /**
   * 加载组件导出处理模块
   */
  async loadExportHandler(type) {
    return this.loadComponentModule(type, 'export');
  }
}

// 创建单例实例
const componentManager = new ComponentManagerService();

export default componentManager; 